package com.lihan.services.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lihan.common.PageResponse;
import com.lihan.common.Result;
import com.lihan.enums.VisibleType;
import com.lihan.mapper.MomentMapper;
import com.lihan.model.dto.MomentFormDTO;
import com.lihan.model.entity.FriendCircle;
import com.lihan.model.vo.MomentVo;
import com.lihan.model.vo.MyFriendsVo;
import com.lihan.services.IFriendService;
import com.lihan.services.IMomentService;
import com.lihan.utils.FastDFSClient;
import com.lihan.utils.PageConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: IMomentServiceImpl
 * Package: com.lihan.services.impl
 * Description:
 *
 * @Author 李涵
 * @Create 2025-05-08 14:59
 * @Version 1.0
 */
@Service
@Slf4j
public class MomentServiceImpl extends ServiceImpl<MomentMapper, FriendCircle> implements IMomentService {

    @Resource
    private IFriendService friendService;

    @Resource
    private FastDFSClient fastDFSClient;

    @Override
    public Result saveMoment(MomentFormDTO form) {

        // 1. 处理图片文件-上传图片文件，返回URL
        List<String> url = new ArrayList<>();
        try {
            MultipartFile[] files = form.getImages();
            if (files != null) {
                for (MultipartFile file : files) {
                    System.out.println(file.getContentType());
                    System.out.println(file.getOriginalFilename());
                    if (!file.isEmpty()) {
                        url.add(fastDFSClient.uploadImage(file));
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 2. 生成朋友圈实体
        FriendCircle friendCircle = FriendCircle.builder()
                .id(Sid.nextShort())
                .userId(form.getUserId())
                .nickname(form.getNickname())
                .avatar(form.getAvatar())
                .content(form.getContent())
                .images(url)
                .visibleType(VisibleType.ALL)
                .build();

        // 3. 保存进数据库
        boolean flag = save(friendCircle);

        if(!flag){
            return Result.errorMsg("朋友圈记录保存失败");
        }

        return Result.ok();
    }

    @Override
    public PageResponse<MomentVo> getMoments(String userId, Long page, Long size) {
        //1. 根据userId查询好友Id列表
        List<MyFriendsVo> friends = friendService.queryMyFriends(userId);
        List<String> friendIds = friends.stream().map(friend -> friend.getFriendUserId()).collect(Collectors.toList());
        friendIds.add(userId);


        //2. 根据好友列表查询朋友圈并进行分页
        //2.1 封装查询条件
        LambdaQueryWrapper<FriendCircle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(FriendCircle::getUserId,friendIds);
        //2.2 封装分页条件
        Page<FriendCircle> pageVo = new Page<>(page, size);
        //2.3 分页查询
        Page<FriendCircle> moments = page(pageVo, queryWrapper);

        log.info(" 朋友圈记录 " + moments);

        moments.getRecords().forEach(moment -> {
            System.out.println("Raw images data: " + moment.getImages());
        });

        Page<MomentVo> momentVoPage = PageConvertUtils.convert(moments, moment -> {
            MomentVo momentVo = MomentVo.builder().nickname(moment.getNickname())
                    .avatar(moment.getAvatar())
                    .createTime(moment.getCreateTime())
                    .images(moment.getImages())
                    .content(moment.getContent())
                    .build();
            return momentVo;
        });

        PageResponse<MomentVo> result = new PageResponse<>(momentVoPage);

        return result;
    }

}
